package com.chuzhiyun.chengguoxy.feature.internship.project;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.chuzhiyun.chengguoxy.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chuzhiyun.chengguoxy.databinding.ActivityProjectInfoBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseActivity;
import com.chuzhiyun.chengguoxy.feature.bean.ProjectInfoBean;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.chuzhiyun.chengguoxy.utlis.ToastCustom;
import com.chuzhiyun.chengguoxy.widgets.InternshipshowView;
import com.codingending.popuplayout.PopupLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class ProjectInfoActivity extends BaseActivity<ActivityProjectInfoBinding> {

    @SuppressWarnings("FieldCanBeLocal")
    private String typeStr = "";
    private String titleStr = "";
    private String employer = "";
    private String startStr = "";
    private String endStr = "";
    private String latitude = "";
    private String longitude = "";
    private String adminDivision = "";
    private String street = "";
    private String dateStr = "";

    private String idStr = "";
    private Boolean isSubmitChange = false;

    final @SuppressLint("SimpleDateFormat")
    SimpleDateFormat dateFormat  = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void initView(View view) {
        viewBinding.navView.ivBack.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                onBackPressed();
            }
        });
    }

    @Override
    public void initData() {

    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public void setListener() {
        typeStr = getIntent().getStringExtra("typeStr");
        if (typeStr.equals("0")){
            //新建实习经历
            viewBinding.navView.tvTitle.setText("新建实习经历");
        }
        if (typeStr.equals("1")){
            //查看
            viewBinding.navView.tvTitle.setText("实习经历");

            viewBinding.companyNameText.setVisibility(View.VISIBLE);
            viewBinding.companyNameEdit.setVisibility(View.GONE);
            viewBinding.positionNameText.setVisibility(View.VISIBLE);
            viewBinding.positionNameEdit.setVisibility(View.GONE);
            viewBinding.chooseAddressRl.setVisibility(View.VISIBLE);
            viewBinding.addressInfoText.setVisibility(View.GONE);
            viewBinding.submitText.setVisibility(View.GONE);



            idStr = getIntent().getStringExtra("id");
            String statusStr = getIntent().getStringExtra("statusStr");
            if (statusStr.equals("进行中")){
                viewBinding.navView.rightTv.setText("编辑");
                viewBinding.navView.rightTv.setVisibility(View.VISIBLE);
                viewBinding.navView.rightTv.setOnClickListener(new CustomClickListener() {
                    @Override
                    protected void onSingleClick() {
                        viewBinding.submitText.setVisibility(View.VISIBLE);
                        isSubmitChange = true;
                    }
                });
            }
            if (statusStr.equals("未开始")){

            }
            if (statusStr.equals("已结束")){

            }
            getInternshipInfo();
        }

        viewBinding.companyNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                employer = viewBinding.companyNameEdit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        viewBinding.positionNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                titleStr = viewBinding.positionNameEdit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        viewBinding.startTimeText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                showBottomTimeChoose("1");
            }
        });
        viewBinding.chooseAddressRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                startActivityForResult(new Intent(mContext, MapLocationActivity.class), 110);
            }
        });


        viewBinding.submitText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isSubmitChange){
                    changeProjectInfo();
                }
                else {
                    createProject();
                }
            }
        });
    }

    private void createProject(){
        if (StringUtils.isBlank(employer)){
            ToastCustom.showErrorToast("请输入公司名称");
            return;
        }
        if (StringUtils.isBlank(titleStr)){
            ToastCustom.showErrorToast("请输入职位名称");
            return;
        }
        if (StringUtils.isBlank(startStr)){
            ToastCustom.showErrorToast("请选择开始日期");
            return;
        }
        String url = NetApi.postProjectInfo();

        HashMap<String,Object> param = new HashMap<>();
        HashMap<String,String> position = new HashMap<>();
        if (!StringUtils.isBlank(street)){
            position.put("street",street);
            position.put("adminDivision",adminDivision);
            position.put("longitude",longitude);
            position.put("latitude",latitude);
        }
        param.put("position",position);
        param.put("start",startStr);
        param.put("employer",employer);
        param.put("title",titleStr);

        Gson gson = new Gson();
        String content = gson.toJson(param);

        showLoadingDialog();
        NetService.getInstance().postJson(url, content, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                dismissLoadingDialog();
                System.out.println(response);
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
                dismissLoadingDialog();
            }
        });
    }

    private void changeProjectInfo(){
        if (StringUtils.isBlank(employer)){
            ToastCustom.showErrorToast("请输入公司名称");
            return;
        }
        if (StringUtils.isBlank(titleStr)){
            ToastCustom.showErrorToast("请输入职位名称");
            return;
        }
        if (StringUtils.isBlank(startStr)){
            ToastCustom.showErrorToast("请选择开始日期");
            return;
        }
        String url = NetApi.putProjectInfo(idStr);

        HashMap<String,Object> param = new HashMap<>();
        HashMap<String,String> position = new HashMap<>();
        if (!StringUtils.isBlank(street)){
            position.put("street",street);
            position.put("adminDivision",adminDivision);
            position.put("longitude",longitude);
            position.put("latitude",latitude);
            param.put("position",position);
        }
        else {
            param.put("position",null);
        }

        param.put("start",startStr);
        param.put("employer",employer);
        param.put("title",titleStr);

        Gson gson = new GsonBuilder().serializeNulls().create();
        String content = gson.toJson(param);

        showLoadingDialog();
        NetService.getInstance().putJson(url, content, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                dismissLoadingDialog();
                if (statusCode==200){
                    onBackPressed();
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
                dismissLoadingDialog();
            }
        });
    }


    private void getInternshipInfo(){
        String url = NetApi.getProjectInfo(idStr);
        NetService.getInstance().get(url, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    ProjectInfoBean bean = gson.fromJson(response, ProjectInfoBean.class);
                    employer = bean.getEmployer();
                    titleStr = bean.getTitle();
                    startStr = bean.getStart();
                    endStr = bean.getEnd();
                    if (bean.getPosition()!=null){
                        street = bean.getPosition().getStreet();
                        adminDivision = bean.getPosition().getAdminDivision()+"";
                        longitude = bean.getPosition().getLongitude()+"";
                        latitude = bean.getPosition().getLatitude()+"";
                    }

                    viewBinding.companyNameEdit.setText(employer);
                    viewBinding.companyNameText.setText(employer);
                    viewBinding.positionNameEdit.setText(titleStr);
                    viewBinding.positionNameText.setText(titleStr);

                    viewBinding.startTimeText.setText(startStr);
                    viewBinding.endTimeText.setText(endStr);
                    viewBinding.addressText.setText(street);
                    viewBinding.addressInfoText.setText(street);
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    private void showBottomTimeChoose(String type){
        dateStr = TimeUtils.getCurrentTime();
        //时间选择器
        View view=View.inflate(mContext, R.layout.timechoose_menu,null);
        PopupLayout popupLayout = PopupLayout.init(mContext,view);
        popupLayout.show();

        TextView monthText = view.findViewById(R.id.month_Text);
        CalendarView calendarView = view.findViewById(R.id.calendarView);
        ImageView calendarLeft = view.findViewById(R.id.left_Text);
        ImageView calendarRight = view.findViewById(R.id.right_Text);
        calendarLeft.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToPre();
            }

        });
        calendarRight.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToNext();
            }

        });
        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                try {
                    dateStr = TimeUtils.strToDateFormat(calendar.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int y = calendar.get(java.util.Calendar.YEAR);
        int m = calendar.get(java.util.Calendar.MONTH);

        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月");
        calendar.setTime(new Date());
        String monthString = df.format(calendar.getTime());
        monthText.setText(monthString);
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onMonthChange(int year, int month) {
                if (month<10)
                {
                    monthText.setText(String.format("%d年0%d月", year, month));
                }
                else
                {
                    monthText.setText(String.format("%d年%d月", year, month));
                }
            }
        });

        TextView cancelText = view.findViewById(R.id.cancel_Text);
        TextView sureText = view.findViewById(R.id.sure_Text);
        cancelText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
            }

        });
        sureText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
                if (StringUtils.isBlank(dateStr)){
                    return;
                }
                if (type.equals("1"))
                {
                    startStr = dateStr;
                    viewBinding.startTimeText.setText(startStr);
                }
                if (type.equals("2"))
                {
                    endStr = dateStr;
                    viewBinding.endTimeText.setText(endStr);
                }
            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==110)
        {
            if (data != null) {
                adminDivision = data.getStringExtra("adCode");
                street = data.getStringExtra("street");
                latitude = data.getStringExtra("latitude");
                longitude = data.getStringExtra("longitude");

                viewBinding.addressInfoText.setText(street);
                viewBinding.addressText.setText(street);
            }
        }
    }

    @Override
    protected ActivityProjectInfoBinding getViewBinding() {
        return ActivityProjectInfoBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }
}